package com.ujson.chat.client.listener;

import com.ujson.base.common.utils.LogUtil;
import com.ujson.chat.client.controller.CommandController;
import com.ujson.chat.client.netty.NettyClient;
import com.ujson.chat.client.session.ClientSession;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.util.concurrent.GenericFutureListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * <h3>ujson-parent</h3>
 * <p>客户端连接监听器</p>
 *
 * @author JerryLiu  a1031757312@gmail.com
 * @version 1.0
 * @date 2021-11-28 21:37
 */
@Slf4j
@Service
public class ClientConnectionListener implements GenericFutureListener<ChannelFuture> {
    @Autowired
    private CommandController commandController;

    private NettyClient nettyClient;

    public ClientConnectionListener setNettyClient(NettyClient nettyClient) {
        if (Objects.isNull(this.nettyClient)) {
            this.nettyClient = nettyClient;
        }
        return this;
    }

    @Override
    public void operationComplete(ChannelFuture f) throws Exception {
        if (f.isSuccess()) {
            ClientSession clientSession = new ClientSession(f.channel());
            commandController.setClientSession(clientSession);
            commandController.setChannel(f.channel());
            LogUtil.info(log, "connect server success.");
            commandController.notifyConnect();
        } else {
            LogUtil.info(log, "connect server error.");
            // 进行连接重试
        }
    }
}
